<?php 
// +----------------------------------------------------------------------
// | RXThinkCMF敏捷开发框架 [ 赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | 版权所有 2018~2023 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | Licensed LGPL-3.0 RXThinkCMF并不是自由软件，未经许可禁止去掉相关版权
// +----------------------------------------------------------------------
// | 官方网站: https://www.rxthink.cn
// +----------------------------------------------------------------------
// | Author: @牧羊人 团队荣誉出品
// +----------------------------------------------------------------------
// | 版权和免责声明:
// | 本团队对该软件框架产品拥有知识产权（包括但不限于商标权、专利权、著作权、商业秘密等）
// | 均受到相关法律法规的保护，任何个人、组织和单位不得在未经本团队书面授权的情况下对所授权
// | 软件框架产品本身申请相关的知识产权，禁止用于任何违法、侵害他人合法权益等恶意的行为，禁
// | 止用于任何违反我国法律法规的一切项目研发，任何个人、组织和单位用于项目研发而产生的任何
// | 意外、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、
// | 附带或衍生的损失等)，本团队不承担任何法律责任，本软件框架禁止任何单位和个人、组织用于
// | 任何违法、侵害他人合法利益等恶意的行为，如有发现违规、违法的犯罪行为，本团队将无条件配
// | 合公安机关调查取证同时保留一切以法律手段起诉的权利，本软件框架只能用于公司和个人内部的
// | 法律所允许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

namespace app\admin\controller;
use app\admin\model\School;
use app\admin\model\Departments;

use app\admin\service\ProfessionalService;

/**
 * 专业管理-控制器
 * @author 牧羊人
 * @since: 2023/08/21
 * Class Professional
 * @package app\admin\controller
 */
class Professional extends Backend
{
    /**
     * 初始化方法
     * @author 牧羊人
     * @since: 2023/08/21
     */
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new \app\admin\model\Professional();
        $this->service = new ProfessionalService();
    }
	
    /**
     * 获取专业列表
     * @return mixed
     * @since 2020/11/20
     * @author 牧羊人
     */
    public function getProfessionalList()
    {
        $result = $this->service->getProfessionalList();
        return $this->jsonReturn($result);
    }

    /**
     * 获取专业列表
     * @return mixed
     * @since 2020/11/20
     * @author 牧羊人
     */
    public function getProfessionalsList()
    {
        $result = $this->service->getList();
        return $this->jsonReturn($result);
    }

    /**
     * 导入Excel
     * @author 牧羊人
     * @since 2021/5/24
     */
    public function importExcel()
    {
        $error = "";
        // 上传文件(非图片)
        $result = upload_file('file', '', $error);
        if (!$result) {
            return $this->jsonReturn(message($error, false));
        }
        // 文件路径
        $filePath = UPLOAD_TEMP_PATH . $result;
        if (!file_exists($filePath)) {
            return $this->jsonReturn(message("文件不存在", false));
        }
        // 读取文件
        $objPHPExcel = \PHPExcel_IOFactory::load($filePath); //获取sheet表格数目
        $sheetCount = $objPHPExcel->getSheetCount(); //默认选中sheet0表
        $sheetSelected = 0;
        $objPHPExcel->setActiveSheetIndex($sheetSelected); //获取表格行数
        $rowCount = $objPHPExcel->getActiveSheet()->getHighestRow(); //获取表格列数
        $columnCount = $objPHPExcel->getActiveSheet()->getHighestColumn();
        // 计数器
        $totalNum = 0;
        // 循环读取行数据
        for ($row = 2; $row <= $rowCount; $row++) {
            // 获取列值
            $dataArr = array();
            // 专业名称
            $dataArr['name'] = $objPHPExcel->getActiveSheet()->getCell("A" . $row)->getValue();
            // 所属组织
            $organ = $objPHPExcel->getActiveSheet()->getCell("B" . $row)->getValue();
            $school = new School();
            $dataArr['organization'] = $school->where(['name'=>trim($organ),'mark'=>1])->value('id');
            // 所属院系
            $superior = $objPHPExcel->getActiveSheet()->getCell("C" . $row)->getValue();
            $departments = new Departments();
            $dataArr['superior'] = $departments->where(['organization'=>$dataArr['organization'],'name'=>trim($superior),'mark'=>1])->value('id');

            $dataArr['type'] = $objPHPExcel->getActiveSheet()->getCell("D" . $row)->getValue()=='自然院系'?1:2;

            // 状态
            $status = $objPHPExcel->getActiveSheet()->getCell("E" . $row)->getValue();
            $dataArr['status'] = $status == "正常" ? 1 : 2;
            // 排序
            $dataArr['sort'] = $objPHPExcel->getActiveSheet()->getCell("F" . $row)->getValue();
            // 备注
            $dataArr['note'] = $objPHPExcel->getActiveSheet()->getCell("G" . $row)->getValue();

            $ids = $this->model->where(['name'=>$dataArr['name'],'organization'=>$dataArr['organization'],'superior'=>$dataArr['superior'],'mark'=>1])->value('id');
            if ($ids) {
               $dataArr['id'] = $ids;
            }
            // 插入数据
            $result = $this->model->edit($dataArr);
            if ($result) {
                $totalNum++;
            }
        }
        return $this->jsonReturn(message("本次共导入{$totalNum}条数据", true));
    }

    /**
     * 导出Excel
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     * @since 2021/3/25
     * @author 牧羊人
     */
    public function exportExcel()
    {
        // 参数
        $param = request()->param();
        // 查询条件
        $map = [];

        // 所属组织
        $organization = isset($param['organization']) ? (int)$param['organization'] : '';
        if ($organization) {
            $map[] = ['organization', '=', $organization];
        }

        // 所属院系
        $superior = isset($param['superior']) ? (int)$param['superior'] : '';
        if ($superior) {
            $map[] = ['superior', '=', $superior];
        }


        // 专业名称
        $name = isset($param['name']) ? trim($param['name']) : '';
        if ($name) {
            $map[] = ['name', 'like', "%{$name}%"];
        }

        // 状态
        $status = isset($param['status']) ? (int)$param['status'] : 0;
        if ($status) {
            $map[] = ['status', '=', $status];
        }
        $map[] = ['mark', "=", 1];
        // 获取导出的数据源
        $list = $this->model->where($map)->select()->toArray();

        // 实例化PHPExcel类
        $objPHPExcel = new \PHPExcel();
        // 激活当前的sheet表
        $objPHPExcel->setActiveSheetIndex(0);
        //5.设置表格头（即excel表格的第一行）
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '专业名称')
            ->setCellValue('B1', '所属组织')
            ->setCellValue('C1', '院系名称')
            ->setCellValue('D1', '院系类型')
            ->setCellValue('E1', '状态')
            ->setCellValue('F1', '显示顺序')
            ->setCellValue('G1', '备注');
        // 设置表格头水平居中
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('B1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('C1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('D1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('E1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('F1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('G1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //设置列水平居中
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('B')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('C')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('D')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('E')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('F')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('G')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        // 设置单元格宽度
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('A')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('C')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('D')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('E')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('F')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('G')->setWidth(10);
        $school = new School();
        $departments = new Departments();
        // 循环刚取出来的数组，将数据逐一添加到excel表格。
        for ($i = 0; $i < count($list); $i++) {


            $organization = $school->where('id',$list[$i]['organization'])->value('name');

            $superior = $departments->where('id',$list[$i]['superior'])->value('name');

            $objPHPExcel->getActiveSheet()->setCellValue('A' . ($i + 2), $list[$i]['name']);// 专业名称
            $objPHPExcel->getActiveSheet()->setCellValue('B' . ($i + 2), $organization);// 所属学校
            $objPHPExcel->getActiveSheet()->setCellValue('C' . ($i + 2), $superior);// 所属院系
            $objPHPExcel->getActiveSheet()->setCellValue('D' . ($i + 2), $list[$i]['type']==1?'自然院系':'体育院系');// 院系类型
            $objPHPExcel->getActiveSheet()->setCellValue('E' . ($i + 2), $list[$i]['status']==1 ? "正常" : "停用");// 状态
            $objPHPExcel->getActiveSheet()->setCellValue('F' . ($i + 2), $list[$i]['sort']);// 排序
            $objPHPExcel->getActiveSheet()->setCellValue('G' . ($i + 2), $list[$i]['note']);// 备注
        }
        // 设置保存的Excel表格名称
        $filename = '专业管理_' . date('YmdHis', time()) . ".xlsx";
        // 设置当前激活的sheet表格名称
        $objPHPExcel->getActiveSheet()->setTitle('专业管理');

        // 保存本地文件
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        try {
            // 保存文件
            $objWriter->save(UPLOAD_TEMP_PATH . "/" . $filename);
        } catch (Exception $e) {
            echo "文件保存失败：" . $e->getMessage();
        }
        return download(UPLOAD_TEMP_PATH . "/" . $filename, $filename);
        // 文件地址
//        $filePath = get_image_url('/uploads'.str_replace(ATTACHMENT_PATH, "", UPLOAD_TEMP_PATH . "/" . $filename));
//        return $this->jsonReturn(message("操作成功", true, $filePath));
    }
                        	                            
}